package com.example.demo.controllers.manage;

import com.example.demo.exception.UnauthorizedException;
import com.example.demo.mapper.UserMapper;
import com.example.demo.model.dto.*;
import com.example.demo.model.entity.audit.AuditRecord;
import com.example.demo.model.entity.user.User;
import com.example.demo.model.enums.AuditResult;
import com.example.demo.model.vo.StudentPaperVO;
import com.example.demo.model.vo.StudentUpdateVO;
import com.example.demo.security.JwtTokenProvider;
import com.example.demo.service.ProfileService;
import com.example.demo.service.TeacherManageService;
import com.example.demo.utils.ResponseUtil;
import com.github.pagehelper.PageInfo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.ExampleObject;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.Min;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api/v1/admin/teacher")
@RequiredArgsConstructor
@SecurityRequirement(name = "bearerAuth")
@Tag(name = "教师管理", description = "教师对学生和论文的管理接口")
public class TeacherManageController {

    private final TeacherManageService teacherManageService;
    private final ProfileService profileService;
    private final UserMapper userMapper;
    private final JwtTokenProvider jwtTokenProvider;

    @GetMapping("/students")
    @Operation(
            summary = "获取关联学生列表",
            description = "获取当前教师关联的所有学生信息",
            responses = {
                    @ApiResponse(
                            responseCode = "200",
                            description = "成功获取学生列表",
                            content = @Content(
                                    schema = @Schema(implementation = ResponseResult.class),
                                    examples = @ExampleObject(
                                            value = "{\"code\":200,\"message\":\"success\",\"data\":[{\"userId\":1,\"username\":\"student1\"}]}"
                                    )
                            )
                    ),
                    @ApiResponse(responseCode = "403", description = "无权限访问"),
                    @ApiResponse(responseCode = "500", description = "服务器内部错误")
            }
    )
//    @PreAuthorize("hasRole('TEACHER')")
    public ResponseEntity<ResponseResult<List<User>>> getRelatedStudents(
            @RequestHeader(name = "Authorization") String authHeader) {

        // 从JWT令牌中获取教师ID
        String token = authHeader.substring(7);
        Long teacherId = jwtTokenProvider.getUserIdFromToken(token);

        log.info("当前教师ID: {}", teacherId);
        List<User> students = teacherManageService.getRelatedStudents(teacherId);

        log.info("返回数据："+ResponseUtil.success(students).toString());

        return ResponseUtil.success(students);
    }

    @GetMapping("/papers")
    @Operation(
            summary = "获取学生论文列表",
            description = "分页获取关联学生的论文信息",
            parameters = {
                    @Parameter(name = "pageNum", description = "页码，从1开始", in = ParameterIn.QUERY, example = "1"),
                    @Parameter(name = "pageSize", description = "每页数量", in = ParameterIn.QUERY, example = "10")
            }
    )
//    @PreAuthorize("hasRole('TEACHER')")
    public ResponseEntity<ResponseResult<PageResult<StudentPaperVO>>> getStudentPapers(
            @RequestHeader(name = "Authorization") String authHeader,
            @RequestParam(defaultValue = "1") @Min(1) int pageNum,
            @RequestParam(defaultValue = "10") @Min(1) int pageSize) {

        // 从JWT令牌中获取教师ID
        String token = authHeader.substring(7);
        Long teacherId = jwtTokenProvider.getUserIdFromToken(token);

        PageInfo<StudentPaperVO> pageInfo = teacherManageService.getStudentPapers(teacherId, pageNum, pageSize);
        log.info("返回数据："+ResponseUtil.success(new PageResult<>(pageInfo)).toString());
        return ResponseUtil.success(new PageResult<>(pageInfo));
    }

    @PostMapping("/papers/{paperId}/audit")
    @Operation(
            summary = "审核论文",
            description = "审核学生论文并记录审核信息",
            requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody(
                    description = "审核请求",
                    content = @Content(
                            schema = @Schema(implementation = PaperAuditRequest.class),
                            examples = @ExampleObject(
                                    value = "{\"result\":\"PASS\",\"comment\":\"论文质量很高\"}"
                            )
                    )
            )
    )
//    @PreAuthorize("hasRole('TEACHER')")
    public ResponseEntity<ResponseResult<Void>> auditPaper(
            @RequestHeader(name = "Authorization") String authHeader,
            @PathVariable Long paperId,
            @Valid @RequestBody PaperAuditRequest request) {

        // 从token获取当前教师ID
        String token = authHeader.substring(7);
        Long teacherId = jwtTokenProvider.getUserIdFromToken(token);

        // 调用服务层时传入教师ID
        teacherManageService.auditPaper(paperId, teacherId, request.getResult(), request.getComment());
        return ResponseUtil.success();
    }

    @GetMapping("/audit-records")
    @Operation(
            summary = "获取审核记录",
            description = "分页获取当前教师的审核记录，可按结果筛选",
            parameters = {
                    @Parameter(name = "pageNum", description = "页码", in = ParameterIn.QUERY),
                    @Parameter(name = "pageSize", description = "每页数量", in = ParameterIn.QUERY),
                    @Parameter(name = "result", description = "审核结果筛选", in = ParameterIn.QUERY)
            }
    )
//    @PreAuthorize("hasRole('TEACHER')")
    public ResponseEntity<ResponseResult<PageResult<AuditRecord>>> getAuditRecords(
            @RequestParam(defaultValue = "1") @Min(1) int pageNum,
            @RequestParam(defaultValue = "10") @Min(1) int pageSize,
            @RequestParam(required = false) AuditResult result) {

        PageInfo<AuditRecord> pageInfo = result == null
                ? teacherManageService.getAuditRecords(pageNum, pageSize)
                : teacherManageService.getAuditRecords(pageNum, pageSize, result);

        return ResponseUtil.success(new PageResult<>(pageInfo));
    }

    @PutMapping("/students/{studentId}")
    @Operation(
            summary = "修改学生信息",
            description = "修改关联学生的基本信息",
            requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody(
                    description = "学生信息更新请求",
                    content = @Content(schema = @Schema(implementation = StudentUpdateVO.class))
            )
    )
//    @PreAuthorize("hasRole('TEACHER')")
    public ResponseEntity<ResponseResult<Void>> updateStudentInfo(
            @PathVariable @Parameter(description = "学生ID", required = true) Long studentId,
            @Valid @RequestBody StudentUpdateVO updateVO) {

        teacherManageService.updateStudentInfo(studentId, updateVO);
        return ResponseUtil.success();
    }

    @DeleteMapping("/students/{studentId}")
    @Operation(
            summary = "解除学生关联",
            description = "解除关联并删除学生账号（需确认无未完成的论文审核）"
    )
//    @PreAuthorize("hasRole('TEACHER')")
    @Transactional
    public ResponseEntity<ResponseResult<Void>> removeStudentRelation(
            @PathVariable @Parameter(description = "学生ID", required = true) Long studentId) {

        if (teacherManageService.hasPendingAudits(studentId)) {
            return ResponseUtil.badRequest("该学生有待审核的论文，不能解除关联");
        }

        teacherManageService.removeStudentRelation(studentId);
        profileService.deleteUserWithPermissionCheck(studentId);
        return ResponseUtil.success();
    }
}